﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using xplang.run;
using xplang.abstractions;
using System.Diagnostics;

namespace xplang.statements
{
  [DebuggerDisplay("while{expression}{statement}")]
  public class While : Statement
  {

    public While(Expression expression, Expression statement)
    {
      this.expression = expression;
      this.statement = statement;
    }

    public readonly Expression expression;
    public readonly Expression statement;

    public override Value doIt(Value[] heap, ref FlowState state)
    {
      while ((bool)(expression.doIt(heap, ref state).pointer))
      {
        if (state != FlowState.Normal)
          return null;
        statement.doIt(heap, ref state);
        if (state != FlowState.Normal)
          if (state == FlowState.ExitFromBlock)
          {
            state = FlowState.Normal;
            break;
          }
          else
            return null;
      }
      return null;
    }

    public override bool isBlock()
    {
      return true;
    }

    //public override void save(Scope scope, SourceBuilder target)
    //{
    //    target.write("return");
    //    if (expression != null)
    //    {
    //        target.write(" ");
    //        expression.save(scope,target);
    //    }
    //    target.writeln(";");
    //}

    //public override void toCSharp(Scope scope, SourceBuilder target)
    //{
    //    target.write("return");
    //    if (expression != null)
    //    {
    //        target.write(" ");
    //        expression.toCSharp(scope, target);
    //    }
    //    target.writeln(";");
    //}

    //public override void toJavaScript(Scope scope, SourceBuilder target)
    //{
    //    target.write("return");
    //    if (expression != null)
    //    {
    //        target.write(" ");
    //        expression.toCSharp(scope, target);
    //    }
    //    target.writeln(";");
    //}
  }
}
